package com.woniuxy.controller;

import com.aliyun.oss.OSSClient;
import com.woniuxy.entity.UploadResult;
import com.woniuxy.entity.utils.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @Author: 马宇航
 * @Do: oss上传controller接口
 * @DateTime: 22/06/29/0029 上午 11:37
 * @Component: 成都蜗牛学苑
 **/
@RestController
@RequestMapping("/oss")
public class OssController {
    @Resource
    OSSClient ossClient;//oss框架提供的客户端，用于和阿里云服务进行交互
    //演示简化配置
    private static final String BUCKETNAME = "myh-java87";//刚创建的桶的名字
    /**
     * <img src="https://woniumd.oss-cn-hangzhou.aliyuncs.com/java/mayuhang/202206291141111.png"/>
    */
    private String baseUrl = "https://myh-java87.oss-cn-hangzhou.aliyuncs.com/";
    @RequestMapping("/upload")
    public ResponseEntity upload(MultipartFile file) throws IOException {
        //1.获取文件名称
        String filename = file.getOriginalFilename();
        //2.获取文件流
        InputStream inputStream = file.getInputStream();
        //3.使用刚注入的ossClient客户端来进行传输
        ossClient.putObject(BUCKETNAME,filename,inputStream);
        //4.设置文件有效时长 60天
        Date date = new Date(System.currentTimeMillis() + 1000 * 3600 * 24 * 60);
        //5.上传并获取到url
        URL url = ossClient.generatePresignedUrl(BUCKETNAME, filename, date);
        UploadResult uploadResult = new UploadResult(filename, url.toString());
        ResponseEntity success = ResponseEntity.SUCCESS;
        success.put("uploadResult",uploadResult);
        success.put("baseurl",baseUrl+filename);
        return success;
    }
    //删除文件
    @PostMapping("/del")
    public ResponseEntity del(String fileName){
        //找到桶，删掉桶中的对应文件
        ossClient.deleteObject(BUCKETNAME,fileName);
        return  ResponseEntity.SUCCESS;
    }
}
